package com.motorola.dp.jenkinsmonitor.service.util.collections;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.stereotype.Service;

import com.motorola.dp.jenkinsmonitor.model.util.collections.Predicate;
import com.motorola.dp.jenkinsmonitor.model.util.collections.Transformer;

@Service("collectionsService")
public class DefaultCollectionsService implements CollectionsService {

    public <T> Collection<T> filter(Collection<T> target, Predicate<T> predicate) {
        return filterAndTransform(target, predicate, emptyTransformer(target));
    }

    public <T> Collection<T> filterAndTransform(Collection<T> target,
            Predicate<T> predicate, Transformer<T> transformer) {
        Collection<T> result = new ArrayList<T>();
        for (T element: target) {
            if (predicate.applies(element)) {
                T transformedElement = transformer.transform(element);
                result.add(transformedElement);
            }
        }
        return result;
    }

    @SuppressWarnings("unused")
    private static <T> Transformer<T> emptyTransformer(Collection<T> target) {
        return new Transformer<T>() {
            public T transform(T object) {
                return object;
            }
        };
    }

}
